package com.yj.springbootstudy.mulThread.imooc.juctools;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier 循环栅栏的使用
 */
public class CyclicBarrierTest {

    private static int threadCount = 5;

    private static Runnable runnable = ()->{
        System.out.println("所有人集合完毕，开始启动车辆！");
    };
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(threadCount,runnable);


    public static void main(String[] args) {
        for (int i = 0; i < threadCount ; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    System.out.println(finalI + "出门");
                    Thread.sleep(new Random().nextInt(5000));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    System.out.println("所有同学集合完毕！");
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

}
